﻿using TheLocal.Core;
using TheLocal.Model;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System;
using TheLocal.Common;
using System.Diagnostics;

namespace TheLocal.ViewModel
{
    public class NewsPageViewModel
    {
        private readonly NewsListViewModel newsList;
        private SynchronizationContext mainContext;
        private Downloader downloader;

        public NewsPageViewModel()
        {
        }

        public NewsPageViewModel(NewsListViewModel newsList, Country selectedCountry, Category selectedCategory)
        {
            this.newsList = newsList;
            this.SelectedCountry = selectedCountry;
            this.SelectedCategory = selectedCategory;
        }

        private void StartDownload(Country selectedCountry, Category selectedCategory)
        {
            this.downloader = new Downloader(LoadNewsItems);
            Category category = selectedCountry.Categories.Where(currentCategory => currentCategory.Name == selectedCategory.Name).FirstOrDefault();
            downloader.Download(string.Format("{0}{1}/{2}", Constants.WebsiteHost, selectedCountry.Code, category.Postfix));
            this.mainContext = SynchronizationContext.Current;
        }

        public Country SelectedCountry
        {
            get;
            set;
        }

        public Category SelectedCategory
        {
            get;
            set;
        }

        public NewsListViewModel NewsList
        {
            get
            {
                return this.newsList;
            }
        }

        public void GoBack()
        {
            if (!this.downloader.DownloadComplete)
            {
                this.downloader.Dispose();
                this.downloader = null;
            }
            else
            {
                this.newsList.Clear();
            }
        }

        public void OnNavigatedTo()
        {
            StartDownload(this.SelectedCountry, this.SelectedCategory);
        }

        private void LoadNewsItems(string html)
        {
            SynchronizationContextExtentions.InvokeIfRequired(this.mainContext, () =>
                {
                    Parser parser = new Parser();

                    foreach (NewsItem newsItems in parser.GetNewsSummaryFromHtml(html))
                    {
                        newsItems.ResolveFullImagePath(this.SelectedCountry);
                        this.newsList.Add(newsItems);
                    }
                });
        }
    }
}
